package com.gitee.hifong45;

import cn.hutool.core.util.XmlUtil;

import java.io.BufferedWriter;
import java.util.Iterator;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPathConstants;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.CharsetUtil;

public class Xml extends XmlUtil{
    public static void insertAfter(Node parentNode, Node newChild, Node refChild) {
		parentNode.insertBefore(newChild, refChild); // 在参考节点前部添加新节点
		Node refNew = refChild.cloneNode(true);
		parentNode.removeChild(refChild); // 删除参考节点
		parentNode.insertBefore(refNew, newChild); // 在新节点前添加参考节点的克隆对象
	}

	public static Element createElementText(Document doc, String tagName, String textContext) {
		Element ele = doc.createElement(tagName);
		ele.setTextContent(textContext);
		return ele;
	}
	public static Element createElementChild(Document doc, String tagName, Node newChild) {
		Element ele = doc.createElement(tagName);
		ele.appendChild(newChild);
		return ele;
	}
	
	public static void toFile(Document doc, String path, int indent) {
        if(indent < 2) {
            indent = 2;
        }
        String charsetName = doc.getXmlEncoding();
		BufferedWriter writer = null;
		try {
			writer = FileUtil.getWriter(path, CharsetUtil.charset(charsetName), false);
			XmlUtil.write(doc, writer, charsetName, indent);
		} finally {
			IoUtil.close(writer);
		}
	}

    
	public void readXPath(Document docResult) {
		String xpath = "//df:project/df:properties/df:project.build.time";
		// xpath = "//df:project/df:message";
		CustomNamespaceContext context = new CustomNamespaceContext();
		Object value = XmlUtil.getByXPath(xpath, docResult, XPathConstants.STRING, context);
		Console.log("{} result= {}", xpath, value);
	}
	public class CustomNamespaceContext implements NamespaceContext{  
        public String getNamespaceURI(String prefix) {  
            if(prefix.equals("ns")){  
                return "http://www.tibco.com/cdc/liugang/ns";  
            }else if(prefix.equals("tg")){  
                return "http://www.tibco.com/cdc/liugang/tg";  
            }else if(prefix.equals("df")){  
                return "http://maven.apache.org/POM/4.0.0";  
            }  
            return XMLConstants.NULL_NS_URI;  
        }  
        public String getPrefix(String namespaceURI) {  
            return null;
        }  
        public Iterator<String> getPrefixes(String namespaceURI) {  
            return null;
        }  
    }
}
